package com.brand.prisd.ViewHolder;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.brand.prisd.R;
import com.brand.prisd.activity.ControlSwitchActivity;
import com.brand.prisd.bean.SwitchBean;
import com.brand.prisd.sp.MySharedPreferences;
import com.brand.prisd.utils.DensityUtil;
import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.api.IResultCallback;
import com.tuya.smart.sdk.api.ITuyaDevice;
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener;
import com.tuya.smart.sdk.bean.DeviceBean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by HJ on 2019/1/3.
 */
public class Type7ViewHolder extends RecyclerView.ViewHolder implements ITuyaSmartActivatorListener, IDevListener, View.OnClickListener {

    @BindView(R.id.iv_deviceIcon)
    ImageView ivDeviceIcon;
    @BindView(R.id.tv_deviceName)
    TextView tvDeviceName;
    @BindView(R.id.tv_deviceState)
    TextView tvDeviceState;
    @BindView(R.id.cl_container)
    ConstraintLayout clContainer;
    @BindView(R.id.iv_threePoints)
    ImageView ivThreePoints;
    private static Context context;
    private SwitchBean switchBean;
    private static ITuyaDevice mDevice;
    private PopupWindow pw;
    private boolean isDelete;

    public Type7ViewHolder(@NonNull View itemView) {
        super(itemView);
        context = itemView.getContext();
        ButterKnife.bind(this, itemView);
//        if (isDelete){
        initMDevice();
//        }
        initRVItem();
        initPopupWindow();
    }

    private void initRVItem() {
        if (mDevice != null) {
            clContainer.setVisibility(View.VISIBLE);
        } else {
            clContainer.setVisibility(View.GONE);
        }
    }

    private void initMDevice() {
        String devId = MySharedPreferences.Build(context).getString("deviceId", null);
        Logger.i("devId: " + devId);
        if (devId != null) {
            //根据设备id初始化设备控制类
            mDevice = TuyaHomeSdk.newDeviceInstance(devId);
            /**
             * 设备对象。该设备的所有dp变化都会通过callback返回。
             *
             * 初始化设备之前，请确保已经初始化连接服务端，否则无法获取到服务端返回信息
             */
            mDevice.registerDevListener(this);
        }
    }

    private void initPopupWindow() {
        pw = new PopupWindow();
        View inflate = View.inflate(context, R.layout.popupwindow_item, null);
        Button btn_delete = inflate.findViewById(R.id.btn_delete);
        btn_delete.setOnClickListener(this);
        pw.setContentView(inflate);
        pw.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pw.setOutsideTouchable(true);
        pw.setFocusable(true);// 获取焦点。否则用户不能对PopupWindow视图进行交互
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_delete:
                if (mDevice != null)
                    mDevice.removeDevice(new IResultCallback() {
                        @Override
                        public void onError(String errorCode, String errorMsg) {
                            switch (errorCode) {
                                case "11002":
                                    tvDeviceState.setText("设备被移除");
                                    ivDeviceIcon.setClickable(false);
                                    tvDeviceName.setClickable(false);
                                    tvDeviceState.setClickable(false);
                                    break;
                                default:
                                    Logger.e("errorCode: " + errorCode + " " + "errorMsg: " + errorMsg);
                                    Toast.makeText(context, "删除失败！" + errorMsg, Toast.LENGTH_SHORT).show();
                                    isDelete = false;
                                    clContainer.setVisibility(View.VISIBLE);
                                    break;
                            }

                        }

                        @Override
                        public void onSuccess() {
                            Toast.makeText(context, "删除成功！", Toast.LENGTH_SHORT).show();
                            isDelete = true;
                            clContainer.setVisibility(View.GONE);
                        }
                    });
                pw.dismiss();
                break;
        }
    }

    @OnClick({R.id.iv_deviceIcon, R.id.tv_deviceName, R.id.iv_threePoints})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_threePoints:
//                pw.showAtLocation(ivThreePoints, Gravity.BOTTOM, 0, -R.dimen.y30);
                pw.showAsDropDown(ivThreePoints, 0, DensityUtil.dip2px(context, -20));
                break;
            case R.id.iv_deviceIcon:
            case R.id.tv_deviceName:
                context.startActivity(new Intent(context, ControlSwitchActivity.class));
                break;

        }

    }

    public void getPosition(int position) {

    }


    private Handler h = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setDevice();
                    break;
                case 1:

                    break;
            }
            return false;
        }
    });

    private void setDevice() {
        boolean isOnline = switchBean.getState();
        if (isOnline) {
            tvDeviceName.setText(switchBean.getDeviceName());
            tvDeviceState.setText("设备在线");
            Glide.with(context).load(switchBean.getIconUrl()).into(ivDeviceIcon);
        } else {
            tvDeviceState.setText("设备离线");
            String name = MySharedPreferences.Build(context).getString("deviceName", null);
            if (name != null) {
                tvDeviceName.setText(name);
            } else {
                tvDeviceName.setText("未知设备");
            }
            String url = MySharedPreferences.Build(context).getString("iconUrl", null);
            if (url != null) {
                Glide.with(context).load(url).into(ivDeviceIcon);
            } else {
                ivDeviceIcon.setImageResource(R.mipmap.ic_launcher_round);
            }

        }
    }


    @Override
    public void onError(String s, String s1) {
        Logger.e("s: " + s + "  " + "s1: " + s1);
    }

    @Override
    public void onActiveSuccess(DeviceBean deviceBean) {

        String devId = deviceBean.getDevId();
        Logger.i("deviceBean.getDevId(): " + devId);
        String deviceName = deviceBean.getName();
        String iconUrl = deviceBean.getIconUrl();
        MySharedPreferences.Build(context).putString("devId", devId);
        MySharedPreferences.Build(context).putString("deviceName", deviceName);
        MySharedPreferences.Build(context).putString("iconUrl", iconUrl);
    }

    @Override
    public void onStep(String s, Object o) {
        Logger.d("s: " + s + "  " + "o: " + o);
    }

    @Override
    public void onDpUpdate(String devId, String dpStr) {
        //dp数据更新:devId 和相应dp数据
        Logger.i("dp数据更新\n" + "devId: " + devId + "   " + "dpStr: " + dpStr);
    }

    @Override
    public void onRemoved(String devId) {
        //设备被移除
        Logger.w("设备被移除\n" + "devId: " + devId);
        if (mDevice != null) {
            mDevice.unRegisterDevListener();
            mDevice.onDestroy();
            clContainer.setVisibility(View.GONE);

        }
    }

    @Override
    public void onStatusChanged(String devId, boolean isOnline) {

        //设备在线状态，online
        switchBean.setState(isOnline);
        h.sendEmptyMessage(0);
        if (!isOnline) {
            if (mDevice != null) {
                mDevice.unRegisterDevListener();
                mDevice.onDestroy();
            }
        }
        Logger.w("设备在线状态\n" + "devId: " + devId + "  " + "isOnline: " + isOnline);
    }

    @Override
    public void onNetworkStatusChanged(String devId, boolean status) {
        //网络状态监听
        Logger.w("网络状态监听: " + status);
        if (status) {
            Logger.i("设备有网络连接\n" + "devId: " + devId);
        } else {
            Logger.w("设备无网络连接\n" + "devId: " + devId);
        }
    }

    @Override
    public void onDevInfoUpdate(String devId) {
        //设备信息变更，目前只有设备名称变化，会调用该接口
        Logger.i("设备信息变更，目前只有设备名称变化，会调用该接口\n" + "devId: " + devId);
    }


    public void getDeviceState(int deviceState) {
        switch (deviceState) {
            case 101:
                clContainer.setClickable(false);
                tvDeviceState.setText("设备被移除");
                break;
        }
    }
}
